package nettyTest.netty3Test.decodetest.httpdecode;

import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;

public class HttpTestHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        if (msg instanceof HttpRequest) {
            // 使用postman 发过来json数据进行解析
            FullHttpRequest chunk = (FullHttpRequest) msg;
            ByteBuf jsonBuf = chunk.content();
            String jsonStr = jsonBuf.toString(CharsetUtil.UTF_8);
            JSONObject jsonObj = JSONObject.parseObject(jsonStr);
//            String jobType = jsonObj.getString("good");

            // 发送json数据到页面上
            String str = "{\"hello\":\"world\"}";
            ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.buffer();
            byteBuf.writeBytes(str.getBytes());
            DefaultFullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
//                                    httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8"); // 文本
            httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8");
            httpResponse.content().writeBytes(byteBuf);
            ctx.writeAndFlush(httpResponse).addListener(ChannelFutureListener.CLOSE);
            ReferenceCountUtil.release(byteBuf);
            ReferenceCountUtil.release(jsonBuf);

//                                    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
//                                    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
//
//                                    StringBuilder buf = new StringBuilder()
//                                            .append("<!DOCTYPE html><h1> hello world </body></html>\r\n");
//                                    ByteBuf buffer = Unpooled.copiedBuffer(buf, CharsetUtil.UTF_8);
//                                    response.content().writeBytes(buffer);
//                                    buffer.release();
//                                    // Close the connection as soon as the error message is sent.
//                                    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        }
    }
}
